<template>
  <div class="star" :class="starType">
    <span 
      v-for="(itemClass,index) in itemClasses" 
      :class="itemClass"
      class="star-item"
      :key='index'  
    ></span>
  </div>
</template>

<script>
  const LENGTH = 5//定义星星的长度
  const CLS_ON = 'on'//全星
  const CLS_HALF = 'half'//半星
  const CLS_OFF = 'off'//无星
  
  export default{
    name:'star',
    props: {
      size: {
        type: Number
      },
      score: {
        type: Number
      }
    },
    computed: {
      starType() {
        return 'star-' + this.size;
      },
      itemClasses() {
        let result = [];//数组存放不同的星星状态
        let score = Math.floor(this.score * 2) / 2;   //  取0.5的倍数，*2向下取0.5
        let hasDecimal = score % 1 !== 0;  //  是否有0.5，既为半颗星
        let integer = Math.floor(score);   //  取得整数部分，整数个星星
        for (let i = 0; i < integer; i++) {
          result.push(CLS_ON);   //  先填入整颗星
        }
        if (hasDecimal) {
          result.push(CLS_HALF);  //  如果有小数则填入一个半颗星，只会一个半颗星
        }
        while (result.length < LENGTH) {
          result.push(CLS_OFF);   //  剩下的填入无星
        }
        return result;
      }
    }
  }
</script>
<style lang="stylus" scoped>
@import "../../commen/stylus/mixin.styl"
  .star
    font-size: 0
    .star-item
      display: inline-block
      vertical-align:top
      background-repeat: no-repeat
    &.star-48
      .star-item
        width: 20px
        height: 20px
        margin-right: 22px
        &:last-child
          margin-right: 0
        &.on
          background-image: url(star48_on@2x.png)
          background-size: 20px
        &.half
          background-image: url(star48_half@2x.png)
          background-size: 20px
        &.off
          bg-image('star48_off')
          background-image: url(star48_off@2x.png)
          background-size: 20px
    &.star-36
      .star-item
        width: 15px
        height: 15px
        margin-right: 6px
        &:last-child
         margin-right: 0
        &.on
          background-image: url(star36_on@2x.png)
          background-size: 15px
        &.half
          background-image: url(star36_half@2x.png)
          background-size: 15px
        &.off
          bg-image('star48_off')
          background-image: url(star36_off@2x.png)
          background-size: 15px
    &.star-24
      .star-item
        width: 10px
        height: 10px
        margin-right: 3px
        &:last-child
          margin-right: 0
        &.on
          background-image: url(star24_on@2x.png)
          background-size: 10px
        &.half
          background-image: url(star24_half@2x.png)
          background-size: 10px
        &.off
          bg-image('star48_off')
          background-image: url(star24_off@2x.png)
          background-size: 10px
</style>
